'use strict';

/**
 * @author   //作者
 * @version  [1.0.0, 2017/8/17]  //时间
 * @see DeviceService.js
 * @since  1.0.0
 */

app.controller('DeviceCtrl',
    ['$scope', '$http', 'dialogs', '$uibModal', '$state', '$timeout', 'DeviceService',
        function ($scope, $http, dialogs, $uibModal, $state, $timeout, DeviceService) {
            var vm = $scope.vm = this;           

            vm.flexigridObj = {};
            DeviceService.getDeviceLocation().then(function (data) {
                vm.archs = data;
            });
            vm.options = DeviceService.getGridOptions();

            //查询
            vm.search = function () {
                var param = angular.copy(vm.query);
                vm.flexigridObj.flexOptions({
                    newp: 1,
                    extParam: param
                }).flexReload();
            }
            //重置
            vm.reset = function () {
                vm.query = {};
                vm.search();
            }

            // 新增
            vm.addDevice = function () {
                $state.go('setting.device.add');
            }
            // 修改
            vm.updateDevice = function (data) {
                if (ISS.isNotEmpty(data)) {
                    $state.go('setting.device.update', {id: data});
                } else {
                    dialogs.notify(undefined, getMessage("common.plzSelectOneRecourd"));
                }
            }
            // 删除
            vm.delDevice = function (index) {
                if (ISS.isNotEmpty(index)) {
                    var result = vm.flexigridObj.getRawRecords(index);
                    // 弹出确认删除提示信息
                    var dlg = dialogs.confirm(undefined, getMessage("common.deleteConfirm"));
                    dlg.result.then(function (data) {
                        DeviceService.delDevice(result).then(function (data) {
                            // 刷新列表
                            vm.flexigridObj.flexReload();
                            //弹出提示信息
                            dialogs.notify(data);
                        });
                    });
                } else {
                    // 提示请选择一条或多条信息
                    dialogs.notify(undefined, getMessage("common.plzSelectOneRecourd"));
                }
            }

          //阈值设置
            vm.setThreshold = function (deviceId) {
            	var selectData = vm.flexigridObj.getCheckedRows();
            	var deviceIds = [];
            	for(var i=0; i<selectData.length; i++){
            		!selectData[i]["deviceType"] && deviceIds.push(selectData[i].deviceId);
            	}
            	
            	if (deviceIds.length){
                    var param = deviceIds;
                    var modalInstance = $uibModal.open({
                        animation: true,
                        backdrop: true,
                        templateUrl: 'app/modules/device/deviceSetList.html',
                        controller: 'DevicesetCtrl',
                        resolve: {
                            param: function () { //param是一个回调函数
                                return param; //这个值会被模态框的控制器获取到
                            }
                        }
                    });
                    modalInstance.result.then(function (result) { //这是一个接收模态框返回值的函数
                        var result  = result; //模态框的返回值
                    });
            	 } else {
                     // 提示请选择一条或多条信息
                     dialogs.notify(undefined, getMessage("common.plzSelectOnePM10Recourd"));
                 }                       
            };

        }
        
    ]);

//模态框控制器
app.controller('DevicesetCtrl', ['$scope', '$state','$filter', '$uibModalInstance','DynamicI18n', 'dialogs', 'DeviceService', 'param',
    function ($scope, $state,$filter, $uibModalInstance, DynamicI18n,  dialogs, DeviceService, param) {

        var vm = $scope.vm = this;
        $scope.param1 = [];        
        $scope.param2 = [];
        vm.Array = [];
        vm.params = DynamicI18n.currentDicts("em.detectionItem"); //引用数据字典检测项
        vm.copyParams = angular.copy(vm.params);
        
        var firstData = param[0];
    	DeviceService.getThreshold(firstData).then(function (data) {
    		var index = -1;;
    		for(var item in data){
    			if(item != "deviceId" && item != "deviceIds"){
    				var type = $filter('detection')(item)+"";
    				if(index < 0){
    					vm["thresholdSet"] = {paramType:type,paramValue:data[item]};
    				}else{
    					vm.Array.push({
    						index:index,
    						param:vm.copyParams
    					});
    					$scope.param1.push(type);
    					$scope.param2.push(data[item]);
    				}
					index ++;
    			}
    		}
    		dealAddOrDel();
    	});
    	      
        vm.saveDevicesetList = function () {
            var result = {}; 
            var deviceIds = "";
            result[$filter('detectionItem')(vm.thresholdSet.paramType)] = vm.thresholdSet.paramValue;
            for(var i=0;i<param.length;i++){
            	deviceIds += param[i] + ",";
            }           
            deviceIds = deviceIds.substring(0,deviceIds.length-1);
            result["deviceIds"] = deviceIds;
            if($scope.param1.length){
            	for(var index=0;index<$scope.param1.length;index++){
            		result[$filter('detectionItem')($scope.param1[index])] = $scope.param2[index];
            	}
            }
            
            DeviceService.setThreshold(result).then(function(data){
            	if (data.success === false) {
                    dialogs.notify(data);
                } else {
                    dialogs.notify(data).closed.then(function () {
                        $uibModalInstance.close();
                    });
                }
			});

        };                

        vm.add = function () {
            vm.Array.push({
            	index:vm.Array.length,
            	param:vm.copyParams
            });
            vm.Array[vm.Array.length-1].param = remove(vm.Array,vm.Array[vm.Array.length-1].index);
        }
        vm.del = function () {
        	if(vm.Array.length == $scope.param1.length){
        		$scope.param1 = $scope.param1.splice(0, $scope.param1.length - 1);
                $scope.param2 = $scope.param2.splice(0, $scope.param2.length - 1);
                dealAddOrDel();
        	}
            vm.Array = vm.Array.splice(0, vm.Array.length - 1);
        }
              
        vm.cancelDevicesetList = function () {
            //dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
            $uibModalInstance.dismiss('cancel');
        };
        
        vm.change = function(index){
        	dealAddOrDel();
        }
        
        //获得筛选后的阈值下拉框选项
        function getSelectedParams(params,index){
        	var tempParams = [];
        	var values = angular.copy($scope.param1);
        	delete values[index];
        	vm.thresholdSet && vm.thresholdSet.paramType && (index >-1) &&values.push(vm.thresholdSet.paramType);
        	for(var j=0;j<params.length;j++){
				if(!isValueInArray(values,params[j].value)){
					tempParams.push(params[j]);
				}
			}
        	return tempParams;
        }
        //判断value在数组array中是否存在
        //存在返回true，否则返回false
        function isValueInArray(array,value){
        	for(var i=0;i<array.length;i++){
        		if(array[i] == value){
        			return true;
        		}
        	}
        	return false;
        }
        //移除已经选择的阈值选项
        function remove(array,index){
        	if(index < 0){
        		vm.params = getSelectedParams(vm.copyParams,index);
        	}
        	else{
        		var tempParams = [];
        		for(var i=0;i<array.length;i++){
        			if(array[i].index == index){
        				tempParams = getSelectedParams(vm.copyParams,index);
        			}
        		}
        		return tempParams;
        	}
        }
        //处理新增、删除、重选后的阈值选项
        function dealAddOrDel(){
        	for(var i=0;i<$scope.param1.length;i++){
    			vm.Array[i].param = remove(vm.Array,i);
			}
        }
    }]);

app.controller('DeviceAddOrUpdateCtrl', ['$scope', '$http', '$state', '$filter', 'dialogs', 'DeviceService', 'DynamicI18n',
    function ($scope, $http, $state, $filter, dialogs, DeviceService, DynamicI18n) {
        var vm = $scope.vm = this;
        vm.device = {deviceId: ''};

        vm.title = "device.addDevice";
        vm.editFlag = false;
        vm.show = false;
        vm.disabled = false;
        function cancel() {
            $state.go('setting.device.list');
        }

        //从数据字典获取摄像头类型
        vm.cameraTypeList = DynamicI18n.currentDicts("device.cameraType");
        if (!ISS.isEmpty($state.params.id)) {
        	vm.disabled = !vm.disabled;
        	vm.show = !vm.show;
        	vm.editFlag = true;
            //修改
            vm.device.id = $state.params.id;
            vm.title = "device.updateDevice";
            
            //查询要修改的
            DeviceService.getDevice(vm.device.id).then(function (data) {
                if (data.success === false) {
                    cancel();
                } else {
                    vm.device = data;
                }
            });
        }
        
        DeviceService.getDeviceLocation().then(function (data) {
        		vm.archs = data;
        	});
        
        vm.cancel = function () {
            cancel();
        };
        // 提交数据
        vm.save = function () {
            if (vm.editFlag) {
                vm.device.arch.createTime = "";
                DeviceService.updateDevice(angular.copy(vm.device)).then(function (data) {
                    if (data.success === false) {
                        dialogs.notify(data);
                    } else {
                        dialogs.notify(data).closed.then(function () {
                            cancel();
                        });
                    }
                });
            } else {
                DeviceService.addDevice(angular.copy(vm.device)).then(function (data) {
                    if (data.success === false) {
                        dialogs.notify(data);
                    } else {
                        dialogs.notify(data).closed.then(function () {
                            cancel();
                        });
                    }
                });
            }
        };

        vm.location = function (lngLat) {
            if (lngLat) {
                vm.device.longitude = lngLat.lng;
                vm.device.latitude = lngLat.lat;
            }
        }
    }]);

